<template>
<div>
  <el-row
    style="margin-bottom: 10px"
  >
    <el-col
      :span="5"
    >
      <el-radio-group
        v-model="enableFilter"
        @change="query()"
      >
        <el-radio
          v-model="addOrModifyUser.gender"
          :label="1" border
        >启用</el-radio>
        <el-radio
          v-model="addOrModifyUser.gender"
          :label="0" border
        >禁用</el-radio>
      </el-radio-group>
    </el-col>
    <el-col
      :span="7"
    >
      <el-input
        style="width: 300px"
        maxlength="50"
        prefix-icon="el-icon-search"
        placeholder="请输入姓名/登录名"
        clearable
        @keyup.enter.native="query()"
        v-model="searchWords">
        <el-button slot="append" icon="el-icon-search" @click="query()"></el-button>
      </el-input>
    </el-col>
    <el-col :span="12" style="text-align: right">
      <div
        style="margin-right: 30px"
      >
        <el-button
          type="primary"
          icon="el-icon-circle-plus"
          @click="initAdd"
        >新增</el-button>
      </div>
    </el-col>
  </el-row>

  <el-table
    :data="userList"
    v-loading="tableLoading"
    highlight-current-row
    @current-change="handleCurrentChange"
    style="width: 100%;">
    <el-table-column
      type="index"
      >
    </el-table-column>
    <el-table-column
      prop="name"
      label="姓名"
      >
    </el-table-column>
    <el-table-column
      prop="loginName"
      label="登录名"
      >
    </el-table-column>
    <el-table-column
      prop="email"
      label="邮箱"
      >
    </el-table-column>
    <el-table-column
      prop="lastLoginTime"
      label="最后登录时间">
    </el-table-column>
    <el-table-column
      prop="isValid"
      label="状态"
    >
      <template slot-scope="scope">
        <el-tag
          :type="scope.row.isValid === 1 ? 'success' : 'danger'"
          disable-transitions>{{scope.row.isValid === 1 ? '启用' : '禁用'}}</el-tag>
      </template>
    </el-table-column>
    <el-table-column
      label="操作"
    >
      <template slot-scope="scope">
        <el-button
          size="mini"
          @click="initEdit(scope.$index, scope.row)">编辑</el-button>
        <el-button
        size="mini"
        :type="scope.row.isValid === 1 ? 'danger' : 'success'"
        @click="handleValid(scope.$index, scope.row)">{{scope.row.isValid == 1 ? '禁用' : '启用'}}</el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-row>
    <el-col
      :span="24"
    >
      <el-pagination
        style="width: 100%"
        @size-change="handleSizeChange"
        @current-change="query"
        :current-page="currentPage"
        :page-sizes="[50, 100, 200, 500, 1000]"
        :page-size="100"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageTotal">
      </el-pagination>
    </el-col>
  </el-row>
  <!--
    添加用户：用户一共有8个属性：
      登录名、昵称、密码、手机号、邮箱、性别、身份证号码、身份标识
  -->
  <el-dialog
    :title="dialogTitle"
    maxheigh="600px"
    :show-close="true"
    :before-close="onDialogClose"
    :visible.sync="dialogVisible"
  >
    <el-form
      ref="userForm"
      :model="addOrModifyUser "
      :inline="true"
      label-width="100px"
      clearable
      status-icon
      label-position="right"
      size="small"
      :rules="formRules"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item
            label="昵称"
            prop="name"
          >
            <el-input
              v-model="addOrModifyUser.name"
              maxlength="20"
              clearable
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="登录名"
            prop="loginName"
          >
            <el-input
              v-model="addOrModifyUser.loginName"
              maxlength="20"
              clearable
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="addOrModify">
        <el-col :span="12">
          <el-form-item
            label="密码"
            prop="password"
          >
            <el-input
              type="password"
              v-model="addOrModifyUser.password"
              maxlength="30"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="重复密码"
            prop="re_password"
          >
            <el-input
              type="password"
              autocomplete="off"
              maxlength="30"
              v-model="addOrModifyUser.re_password"
              clearable
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="性别"
            prop="gender"
          >
            <el-radio-group
              v-model="addOrModifyUser.gender"
            >
              <el-radio
                :label="1" border
              >男</el-radio>
              <el-radio
                :label="2" border
              >女</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号" prop="mobilePhone"   >
            <el-input v-model="addOrModifyUser.mobilePhone" maxlength="15" clearable autocomplete="off"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col
          :span="12"
        >
          <el-form-item
            label="身份证号码"
            prop="idCard"
          >
            <el-input
              v-model="addOrModifyUser.idCard"
              maxlength="18"
              clearable
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="邮箱"
            prop="email"
          >
            <el-input
              type="email"
              v-model="addOrModifyUser.email"
              maxlength="50"
              clearable
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col
          :span="24"
          style="text-align: center"
        >
          <el-form-item
            label="身份标识"
            prop="userType"
          >
            <el-select
              v-model="addOrModifyUser.userType"
              placeholder="请选择身份标识"
            >
              <el-option
                label="管理员"
                :value="1"
              ></el-option>
              <el-option
                label="普通用户"
                :value="2"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template slot="footer">
      <el-row>
        <el-col :span="12" style="text-align: center">
          <el-button type="info" style="width: 150px;" @click="closeDialog" plain>取消</el-button>
        </el-col>
        <el-col :span="12" style="text-align: center">
          <el-button type="primary" style="width: 150px;" @click="submitForm" plain>{{ dialogOkBtnText }}</el-button>
        </el-col>
      </el-row>
    </template>
  </el-dialog>
</div>
</template>

<script>
import valids from '../../util/patterns'

export default {
  name: 'userManager',
  data () {
    // 自定义重复密码验证规则
    var validCheckPass = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('重复密码不能为空'))
      } else if (value === this.addOrModifyUser.password) {
        return callback()
      } else {
        return callback(new Error('两次密码不一致'))
      }
    }
    return {
      // 启用禁用过滤当前值
      enableFilter: 1,
      // 查询关键字
      searchWords: null,
      // 当前页数
      currentPage: 0,
      // 每页大小
      pageSize: 100,
      // 分页总条数
      pageTotal: 0,
      // 加载中遮罩层是否显示
      tableLoading: false,
      // 当前选择行
      currSelectRow: null,
      // 查询结果
      userList: [],
      // 新增修改弹出框是否显示
      dialogVisible: false,
      // 当前新增或修改的用户
      addOrModifyUser: {},
      // true是添加，false是修改
      addOrModify: true,
      // 表单的验证
      formRules: {
        mobilePhone: [
          {validator: valids.validtors.validPhone, trigger: 'blur'},
          {required: true, message: '手机号码不能为空', trigger: 'blur'}
        ],
        password: [
          {validator: valids.validtors.validPassword, trigger: 'blur'},
          {required: true, message: '密码不能为空', trigger: 'blur'}
        ],
        re_password: [
          {validator: validCheckPass, trigger: 'blur'},
          {required: true, message: '确认密码不能为空', trigger: 'blur'}
        ],
        loginName: [
          {validator: valids.validtors.loginName, trigger: 'blur'},
          {required: true, message: '登录名不能为空', trigger: 'blur'}
        ],
        name: [
          {required: true, message: '昵称不能为空', trigger: 'blur'}
        ],
        idCard: [
          {validator: valids.validtors.idCard, trigger: 'blur'},
          {required: true, message: '身份证号不能为空', trigger: 'blur'}
        ],
        email: [
          {validator: valids.validtors.email, trigger: 'blur'},
          {required: true, message: '邮箱不能为空', trigger: 'blur'}
        ],
        gender: [
          {required: true, message: '性别不能为空', trigger: 'blur'}
        ],
        userType: [
          {required: true, message: '用户身份不能为空', trigger: 'blur'}
        ]
      }
    }
  },
  methods: {
    query: function () {
      this.tableLoading = true
      let url = '/api/userserver/user?page='
      url += this.currentPage +
          '&size=' +
          this.pageSize +
          '&words=' +
          (this.searchWords === null ? '' : this.searchWords) +
          '&isValid=' +
          this.enableFilter
      var that = this
      this.$axios({
        method: 'get',
        url: url
      })
        .then(function (res) {
          that.tableLoading = false
          if (res.data.code === 200) {
            that.pageTotal = res.data.data.total
            that.userList = res.data.data.list
          } else {
            that.$msgbox(res.data.message)
          }
        }).catch(function (e) {
          that.tableLoading = false
          console.error(e)
          that.$alert('网络异常，请求失败！', '请求失败', 'error')
        })
    },
    initAdd: function () {
      this.addOrModifyUser = {
        name: '',
        loginName: '',
        password: '',
        re_password: '',
        mobilePhone: '',
        email: '',
        gender: 1,
        idCard: '',
        isValid: 1,
        userType: 2
      }
      // true编辑
      this.addOrModify = true
      this.dialogVisible = true
    },
    submitForm: function () {
      this.$refs['userForm'].validate((valid) => {
        if (valid) {
          if (this.addOrModify) {
            this.commit('post')
          } else {
            this.commit('put')
          }
        }
      })
    },
    commit: function (type) {
      if (!type) {
        this.$msgbox('请求类型异常', '错误', 'error')
      }
      this.$axios({
        method: type,
        url: '/api/userserver/user',
        data: this.addOrModifyUser
      }).then((res) => {
        this.$message({
          showClose: true,
          message: res.data.message,
          type: 'success'
        })
        this.closeDialog()
        this.query()
      }).catch((err) => {
        console.error(err)
      })
    },
    initEdit: function (index, row) {
      this.addOrModifyUser = row
      this.addOrModify = false
      this.dialogVisible = true
    },
    handleValid: function (index, row) {
      let msg = row.isValid === 1 ? '确定禁用该用户？' : '确定启用该用户？'
      this.$confirm(msg)
        .then(_ => {
          row.isValid === 1 ? row.isValid = 0 : row.isValid = 1
          this.addOrModifyUser = row
          this.commit('put')
          this.addOrModifyUser = {}
          this.query()
        })
    },
    handleSizeChange: function (size) {
      this.pageSize = size
      this.query()
    },
    handleCurrentChange: function (cur) {
      this.currSelectRow = cur
    },
    closeDialog: function () {
      this.addOrModifyUser = {}
      if (this.$refs['userForm']) {
        this.$refs['userForm'].resetFields()
      }
      this.dialogVisible = false
    },
    onDialogClose: function (done) {
      this.$confirm('确定关闭？')
        .then(_ => {
          this.closeDialog()
        }).catch(_ => {
          console.log(JSON.stringify(_))
        })
    }
  },
  mounted: function () {
    this.query()
  },
  computed: {
    dialogTitle: function () {
      return this.addOrModify ? '添加用户' : '修改用户'
    },
    dialogOkBtnText: function () {
      return this.addOrModify ? '添加用户' : '保存修改'
    }
  }
}
</script>

<style scoped>
</style>
